package com.rongji.dfish.demo.comm.view;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.rongji.dfish.base.Page;
import com.rongji.dfish.base.Utils;
import com.rongji.dfish.base.util.DateUtil;
import com.rongji.dfish.demo.comm.service.CommService;
import com.rongji.dfish.demo.constant.DemoConstants;
import com.rongji.dfish.demo.entity.CommPost;
import com.rongji.dfish.demo.entity.CommPostReply;
import com.rongji.dfish.demo.entity.PubLoginUser;
import com.rongji.dfish.demo.pub.service.UserService;
import com.rongji.dfish.demo.pub.view.PubView;
import com.rongji.dfish.framework.FilterParam;
import com.rongji.dfish.framework.FrameworkHelper;
import com.rongji.dfish.framework.plugin.file.service.FileService;
import com.rongji.dfish.framework.plugin.file.ui.DefaultUploadFile;
import com.rongji.dfish.ui.Widget;
import com.rongji.dfish.ui.form.Select;
import com.rongji.dfish.ui.form.Text;
import com.rongji.dfish.ui.form.UploadItem;
import com.rongji.dfish.ui.form.Validate;
import com.rongji.dfish.ui.helper.FormPanel;
import com.rongji.dfish.ui.helper.GridPanel;
import com.rongji.dfish.ui.helper.HorizontalGroup;
import com.rongji.dfish.ui.layout.ButtonBar;
import com.rongji.dfish.ui.layout.HorizontalLayout;
import com.rongji.dfish.ui.layout.VerticalLayout;
import com.rongji.dfish.ui.layout.View;
import com.rongji.dfish.ui.layout.grid.GridColumn;
import com.rongji.dfish.ui.layout.grid.Tr;
import com.rongji.dfish.ui.plugin.ueditor.Ueditor;
import com.rongji.dfish.ui.widget.Button;
import com.rongji.dfish.ui.widget.Html;
import com.rongji.dfish.ui.widget.Leaf;
import com.rongji.dfish.ui.widget.PageBar;
import com.rongji.dfish.ui.widget.Split;
import com.rongji.dfish.ui.widget.SubmitButton;
import com.rongji.dfish.ui.widget.TreePanel;


public class CommView {
	
	public static View buildPostListView(PubLoginUser loginUser, FilterParam fp) {
		View view = PubView.buildBodyView().setCls("comm");
		//分为左  右结构
		TreePanel menu = (TreePanel) view.findNodeById(PubView.BODY_MENU);
		fillCommMenu(menu);
	
		CommService commService = FrameworkHelper.getBean(CommService.class);
		Page page=getPage(fp.getValueAsString("cp"));
		String plateId=fp.getValueAsString("plateId");
		String showType=fp.getValueAsString("showType");
		if (Utils.isEmpty(showType)) {
			showType = "0";
		}
		List<CommPost> postList= null;
		if("0".equals(showType)){//根据所属板块查看帖子
			postList = commService.findCommPosts(page, plateId);
		}else if("1".equals(showType)){//查看我的帖子
			postList=commService.findMyCommPosts(page, loginUser.getUserId());
		}
		//内容栏分为标签页布局
		Html mainTitle = (Html) view.findNodeById(PubView.MAIN_TITLE);	
		String title=commService.getPlateName(plateId);
		mainTitle.setText(title+"("+page.getRowCount()+")");

		ButtonBar mainOper = (ButtonBar) view.findNodeById(PubView.MAIN_OPER);
		mainOper.add(new Button("", "我要发帖").setOn(Button.EVENT_CLICK, "VM(this).cmd('toPost','"+plateId+"');"));
		
		VerticalLayout mainDisplay=(VerticalLayout) view.findNodeById(PubView.MAIN_DISPLAY);
		mainDisplay.setCls("post-list bg-white");
		
		GridPanel mainGrid=getGridSet();
		mainGrid.setFocusable(true).setScroll(true);
		
		StringBuilder format=new StringBuilder();
		format.append("javascript: var top='';var setTop='';" +
				"if($pIsTop=='1'){" +
				"top=\"<span class='label alert'>顶</span>\";" +
				"setTop=\"<a class='hidden-for-small view-count' onclick=\\\"VM(this).cmd('setTop','\"+$postId+ \"','');\\\"><i class='eye'></i>取消置顶</a>\";" +
				"}else{" +
				"setTop=\"<a class='hidden-for-small view-count' onclick=\\\"VM(this).cmd('setTop','\"+$postId+ \"','1');\\\"><i class='eye'></i>置顶</a>\";" +
				"} " +
				"return \"<li class='clearfix'>" +
						"<a class='post-avatar' ><img src='m/comm/img/default.png'></a>" +
						"<div class='topic-con'>" +
						"<div class='title'>" +
						"");
//						"\"+top+ \"");
		
		if("0".equals(showType)){//根据所属板块查看帖子
			mainGrid.setPub(new Tr()
					.setHeight(40).setOn(Tr.EVENT_DBLCLICK, "var postId=this.x.data.postId;VM(this).cmd('showReply',postId);"));
			format.append("<div class='title'>"+"\"+top+ \"<a onclick=\\\"VM(this).cmd('showReply','\"+$postId+ \"');\\\">\"+$pTitle+ \"</a></div>" );
		}else if("1".equals(showType)){//查看我的帖子
			mainGrid.setPub(new Tr()
					.setHeight(40).setOn(Tr.EVENT_DBLCLICK, "var postId=this.x.data.postId;VM(this).cmd('toPost','"+plateId+"',postId);"));
			format.append("<div class='title'>"+"\"+top+ \"<a onclick=\\\"VM(this).cmd('toPost','"+plateId+"','\"+$postId+ \"');\\\">\"+$pTitle+ \"</a></div>" );
		}
		format.append("<div class='item clearfix'>" +
			     "<span class='author'>楼主：\"+$pCreator+ \"</span>" +
			     "<span class='pubtime'>发表于：\"+$pTime+ \"</span>" );
		if(loginUser!=null&&DemoConstants.USER_ADMIN.equals(loginUser.getUserId())){
			format.append("\"+setTop+ \"");
		}
		format.append("</div></div></li>\"");
		int columnIndex = 0;
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "postId"));
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "pTitle"));
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "pCreator"));
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "pTime"));
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "pIsTop"));
		mainGrid.addColumn(GridColumn.text(0, "oper", "", "*")
				.setFormat(format.toString()));
		List<Object[]> dataList = new ArrayList<Object[]>();
		UserService userService = FrameworkHelper.getBean(UserService.class);
		if (postList != null) {
			for(CommPost post:postList){
				dataList.add(new Object[]{
						post.getPostId(),
						post.getPostTitle(),
						userService.find(post.getPostCreator()).getUserName(),
						DateUtil.format(post.getCreateTime()),
						post.getIsTop()
				});
			}
		}
		mainGrid.setGridData(dataList);
		mainDisplay.add(mainGrid);
		
		if(page.getPageCount()>1){
			PageBar pageBar=buildPageBar(page);
			pageBar.setSrc("comm/reloadPostList?cp=$0&plateId="+plateId);
			mainDisplay.add(pageBar,"-1");
		}
		
		view.addCommand("reloadPostList",PubView.getAjaxCommand("comm/reloadPostList?showType=$0&plateId=$1"));
		view.addCommand("toPost",PubView.getAjaxCommand("comm/toPost?plateId=$0&postId=$1"));
		view.addCommand("showReply",PubView.getAjaxCommand("comm/showReply?postId=$0"));
		view.addCommand("toReply",PubView.getAjaxCommand("comm/toReply?postId=$0"));
		view.addCommand("saveReply", PubView.getSubmitCommand("comm/saveReply"));
		view.addCommand("setTop", PubView.getAjaxCommand("comm/setTop?postId=$0&setTop=$1"));
//		view.addCommand("reloadMyPostList", PubView.getAjaxCommand("comm/reloadMyPostList"));
		return view;
	}
	
	private static PageBar buildPageBar(Page page) {
		PageBar pageBar=new PageBar("pageBar","page/text");
		pageBar.setBtncount(5).setAlign(PageBar.ALIGN_RIGHT).setHeight(50)
			.setWidth("95%").setNofirstlast(false).setJump(true);
		PubView.fillPagePanel(pageBar, page);
		return pageBar;
	}

	private static void fillCommMenu(TreePanel tree) {
		CommService commService = FrameworkHelper.getBean(CommService.class);
		tree.setCls("bg-menu");
		tree.setPub(new Leaf().setOn(Leaf.EVENT_CLICK, "var id=this.x.id;VM(this).cmd('reloadPostList','0',id);"));
		tree.add(new Leaf("","全部").setFocus(true).setCls("bold"));
//		tree.add(plateLeaf);
//		Leaf plateLeaf=new Leaf("","全部").setFocus(true);
		for(String[] list:commService.getPlateList()){
			tree.add(new Leaf(list[0],list[1]));
		}
		tree.add(new Leaf("","我的帖子").setCls("bold").setOn(Leaf.EVENT_CLICK, "VM(this).cmd('reloadPostList','1');"));
	}
	
	public static Widget<?> buildPostView(CommPost onePost) {
		View view = PubView.buildDialogView();
		CommService commService = FrameworkHelper.getBean(CommService.class);
		FormPanel main = (FormPanel) view.findNodeById(PubView.DIALOG_MAIN);
		
		if (onePost == null) {
			onePost = new CommPost();
		}
//		HorizontalLayout horz=new HorizontalLayout("");
//		main.add(horz,"50");
		main.addHidden("postId", onePost.getPostId());
		List<String[]> plateList=new ArrayList<String[]>();
		plateList.add(new String[]{"","---请选择---"} );
		plateList.addAll(commService.getPlateList());
		HorizontalGroup hg = new HorizontalGroup(null).setHideLabel(true);
		main.add(hg);
		hg.add(new Select("postPlate","所属板块",onePost.getPostPlate(),plateList).setRequired(true).setWidth(120));
		hg.add(new Text("postTitle", "帖子标题", onePost.getPostTitle()).setRequired(true).addValidate(Validate.maxlength(200))
				.setPlaceholder("请输入帖子标题"));
		main.add(new Ueditor("postContent", "帖子内容", onePost.getPostContent()).setRequired(true).setHeight("320")
				.addValidate(Validate.maxlength(4000)).setHideLabel(true));
		FileService fileService=FrameworkHelper.getBean(FileService.class);
		List<UploadItem> fileItems=fileService.findUploadItems(DemoConstants.FILE_LINK_COMM, onePost.getPostId());
		main.add(new DefaultUploadFile("attachFile","发帖附件").setUploadItems(fileItems).setHideLabel(true));
		
		ButtonBar btnBar = (ButtonBar) view.findNodeById(PubView.DIALOG_BTN);
		btnBar.add(0, new SubmitButton("确定").setOn(Button.EVENT_CLICK, "this.cmd('save');"));
		
		view.addCommand("save", PubView.getSubmitCommand("comm/savePost"));
		return view;
	}
	
	public static View buildReplyListView(PubLoginUser loginUser,FilterParam fp) {
		View view = PubView.buildBodyView();
		//分为左  右结构
		TreePanel menu = (TreePanel) view.findNodeById(PubView.BODY_MENU);
		fillCommMenu(menu);
		//内容栏分为标签页布局
		String postId=fp.getValueAsString("postId");
		CommService commService = FrameworkHelper.getBean(CommService.class);
		CommPost post=commService.getCommPost(postId);
		Html mainTitle = (Html) view.findNodeById(PubView.MAIN_TITLE);	
		String title=commService.getPlateName(post.getPostPlate());
		mainTitle.setText(title);
		
		Page page=getPage(fp.getValueAsString("cp"));
		List<CommPostReply> replyList = commService.findCommReplys(page, postId);
	
		VerticalLayout mainDisplay=(VerticalLayout) view.findNodeById(PubView.MAIN_DISPLAY);
		mainDisplay.setScroll(true);
		mainDisplay.setCls("detail_list bg-white");
		if(page.getCurrentPage()<=1){
			HorizontalLayout postContent=bulidPostDetail(post,page.getRowCount());
			mainDisplay.add(postContent,"-1");
		}
//		
		GridPanel mainGrid=getGridSet();
		int columnIndex = 0;
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "replyId"));
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "rCreator"));
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "rContant"));
		mainGrid.addColumn(GridColumn.hidden(columnIndex++, "rTime"));
		mainGrid.addColumn(GridColumn.text(0, "show", "", "*")
		.setFormat("<li class='clearfix'>" +
				"<div class='post-avatar'>" +
						"<a href='javascript:void(0);'>" +
						"<img src='m/comm/img/face48.png'>" +
						"<p class=user_name>$rCreator</p>" +
						"</a>" +
						"</div>" +
						"<div class='detail_con clearfix'>" +
						"<div class='media clearfix'>" +
						"<p class='artivle-left'>$rContant</p>" +
						"</div>" +
						"<p class='from'>" +
						"<span></span><span></span> <span>发表于$rTime</span>" +
						" </p>" +
						" </div></li>"));
		
		List<Object[]> dataList = new ArrayList<Object[]>();
		UserService userService = FrameworkHelper.getBean(UserService.class);
		if (replyList != null) {
			for(CommPostReply reply:replyList){
				dataList.add(new Object[]{
						reply.getPostId(),
						userService.find(reply.getReplyCreator()).getUserName(),
						reply.getReplyContent(),
						DateUtil.format(reply.getCreateTime())
				});
			}
		}
		mainGrid.setGridData(dataList);
		mainDisplay.add(mainGrid,"-1");
		
		PageBar pageBar=buildPageBar(page);
		if(page.getPageCount()>1){
			mainDisplay.add(pageBar,"-1");
			pageBar.setSrc("comm/reloadReplyList?cp=$0&postId="+postId);
		}
		String userName="";
		if(loginUser!=null){
			userName=loginUser.getUserName();
		}
		VerticalLayout replyEditor=buildReplyView(postId,userName);
		mainDisplay.add(new Split().setHeight("20").setStyle("background-color: #F6F9FE;"));
		mainDisplay.add(replyEditor,"-1");
		return view;
	}
	private static HorizontalLayout bulidPostDetail(CommPost post,int count) {
		UserService userService = FrameworkHelper.getBean(UserService.class);
		HorizontalLayout horizontalLayout=new HorizontalLayout("hor");
		horizontalLayout.add(new Html("<li class='clearfix no_border'>"+
						"<div class='post-avatar' style='position: static;'>" +
						"<a href='javascript:void(0);'>" +
						"<img src='m/comm/img/face48.png'>" +
						"<p class='user_name'>"+userService.find(post.getPostCreator()).getUserName()+"</p>" +
						"</a>" +
						"</div></li>").setWidth(150));
		VerticalLayout verticalLayout=new VerticalLayout("");
		verticalLayout.add(new Html("").setHeight(15));
		verticalLayout.add(new Html("<div class='detail_con clearfix'>" +
						"<div class='media clearfix'>" +
						"<div id='data_a_head' class='article_head clearfix'>" +
						"<p class='article-title p-color' style='color:#99ccff'>"+post.getPostTitle()+"</p>" +
						//				"<p class='from'>发表在提问交流</p>" +
						" </div><p></p>" +
						"<p>"+post.getPostContent()+"</p></div>" ));
		
		verticalLayout.add(new Html("").setHeight(25));
		HorizontalLayout foot=new HorizontalLayout("foot");
		FileService fileService=FrameworkHelper.getBean(FileService.class);
		List<UploadItem> fileItems=fileService.findUploadItems(DemoConstants.FILE_LINK_COMM,post.getPostId());
		if(fileItems!=null&&fileItems.size()>0){
			foot.add(new Html("<p style='color:#666; font-size:18px;'>附件</p>").setWidth(50));
		}
		foot.add(new DefaultUploadFile("attachFile","发帖附件").setUploadItems(fileItems).setReadonly(true).setWidth(400));
		foot.add(new Html("<div class='clearfix'></div>"+
							"<div class='clearfix'><span class='icon_right'>"
							+ "<i class='icon_handle icon_comment'></i>"+count
							+"</span></div>"
							+ "<p class='from'><span class='icon_right'><span>楼主</span>"
							+ "<span>|</span><span>发表于 "
							+DateUtil.format(post.getCreateTime())
							+"</span></p>"));
		verticalLayout.add(foot);
		horizontalLayout.add(verticalLayout);
		horizontalLayout.add(new Html("").setWidth(20));
		return horizontalLayout;
	}
	public static VerticalLayout buildReplyView(String postId,String userName) {
		
		VerticalLayout verticalLayout = new VerticalLayout("");
		HorizontalLayout horz=new HorizontalLayout("");
		verticalLayout.add(horz);
		horz.add(new Html("" +
				"<li class='clearfix no_border'>" +
				" <div class='post-avatar' style='position: static;'>" +
				"	<a href='javascript:void(0);'>" +
				"     <img src='m/comm/img/face48.png'> " +
				"	  <p class='user_name'>"+userName+"</p>" +
				"</a>" +
				"</div></li>"),"140");
//		FormPanel main = (FormPanel) view.findNodeById(PubView.DIALOG_MAIN);
		VerticalLayout main=new VerticalLayout("");
		main.setStyle("margin-top: 20px;");
		horz.add(main);
		main.addHidden("postId", postId);
		main.add(new Ueditor("replyContent", "", "").setRequired(true).setHeight(195).setWidth("95%")
				.addValidate(Validate.maxlength(4000)));
		
		ButtonBar btnBar = new ButtonBar("");
		main.add(btnBar);
		btnBar.setWidth("95%").setAlign(ButtonBar.ALIGN_RIGHT).setStyle("margin: 15px 15px;").setWmin(20);
		btnBar.getPub().setCls("btn");
		btnBar.add(0, new SubmitButton("发表").setOn(Button.EVENT_CLICK, "this.cmd('saveReply');"));
		
		horz.setStyle("padding: 10px;");
		return verticalLayout;
	}
	public static GridPanel getGridSet(){
		GridPanel mainGrid=new GridPanel("");
		mainGrid.setStyle("padding:10px;").setWmin(20).setHmin(20);
		mainGrid.setHasTableHead(false);
		mainGrid.setFace("none");
		return mainGrid;
	}
	private static  Page getPage(String cp) {
		Page page = new Page();
		page.setPageSize(15);
		int curPage = 1;
		try {
			curPage = Integer.parseInt(cp);
		} catch (Exception ex) {
			curPage = 1;
		}
		page.setCurrentPage(curPage);
		return page;
	}
	
	public static FilterParam getParam4PostList(HttpServletRequest request) {
		FilterParam fp = new FilterParam();
		fp.registerKey("cp");
		fp.registerKey("plateId");
		fp.registerKey("showType");
		fp.bindRequest(request);
		return fp;
	}
	
	public static FilterParam getParam4ReplyList(HttpServletRequest request) {
		FilterParam fp = new FilterParam();
		fp.registerKey("cp");
		fp.registerKey("postId");
		fp.registerKey("plateId");
		fp.bindRequest(request);
		return fp;
	}
}
